package com.rgsx.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
    private static List<String> urlNotNeedInterceptors;
    static {
        urlNotNeedInterceptors = new ArrayList<String>();

        urlNotNeedInterceptors.add("/user/**");
        urlNotNeedInterceptors.add("/chat/**");
        urlNotNeedInterceptors.add("/swagger-ui.html/**");
        urlNotNeedInterceptors.add("/doc.html");
        urlNotNeedInterceptors.add("/swagger-resources/**");
        urlNotNeedInterceptors.add("/webjars/**");
        urlNotNeedInterceptors.add("/v2/**");
        urlNotNeedInterceptors.add("/swagger/index.html");
//        urlNotNeedInterceptors.add("/uploadFile/**");
    }

    private TokenIntercepter tokenIntercepter;

    @Autowired
    public void setTokenIntercepter(TokenIntercepter tokenIntercepter) {
        this.tokenIntercepter = tokenIntercepter;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 可以添加多个拦截器，一般只添加一个
        // addPathPatterns("/**") 表示对所有请求都拦截
        // .excludePathPatterns("/base/index") 表示排除对/base/index请求的拦截
        // 多个拦截器可以设置order顺序，值越小，preHandle越先执行，postHandle和afterCompletion越后执行
        // order默认的值是0，如果只添加一个拦截器，可以不显示设置order的值

        registry.addInterceptor(tokenIntercepter).addPathPatterns("/**")
                .excludePathPatterns(WebAppConfigurer.urlNotNeedInterceptors).order(0);
        // registry.addInterceptor(userPermissionInterceptorAdapter).addPathPatterns("/**")
        // .excludePathPatterns("/base/index").order(1);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
    }

    //处理静态资源
//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("/static").addResourceLocations("classpath:/static/");
//    }

    /**
     * 图片保存路径，自动从yml文件中获取数据
     *   示例： E:/images/
     */
    @Value("${file-save-path}")
    private String fileSavePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * 配置资源映射
         * 意思是：如果访问的资源路径是以“/images/”开头的，
         * 就给我映射到本机的“E:/images/”这个文件夹内，去找你要的资源
         * 注意：E:/images/ 后面的 “/”一定要带上
         */
        registry.addResourceHandler("/uploadFile/**")
                .addResourceLocations("file:"+fileSavePath);
    }
}

